package net.csdn.business.notify.handler.handler;

import lombok.extern.slf4j.Slf4j;
import net.csdn.business.notify.common.pipeline.domain.TaskInfo;
import net.csdn.business.notify.handler.flowcontrol.FlowControlFactory;
import net.csdn.business.notify.handler.flowcontrol.FlowControlParam;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Objects;


/**
 * @ClassName BaseHandler
 * @Description 消息处理器基类：发送各个渠道的handler
 * @Author zhangyl
 * @Date 2023/11/30 17:06
 */
@Slf4j
public abstract class BaseHandler implements Handler {
    /**
     * 标识渠道的Code
     * 子类初始化的时候指定
     */
    protected Integer channelCode;

    /**
     * 限流相关的参数
     * 子类初始化的时候指定
     */
    protected FlowControlParam flowControlParam;

    @Autowired
    private HandlerHolder handlerHolder;
    @Autowired
    private FlowControlFactory flowControlFactory;

    /**
     * 初始化渠道与Handler的映射关系
     */
    @PostConstruct
    private void init() {
        handlerHolder.putHandler(channelCode, this);
    }


    @Override
    public void doHandler(TaskInfo taskInfo) {
        // 只有子类指定了限流参数，才需要限流
        if (Objects.nonNull(flowControlParam)) {
            flowControlFactory.flowControl(taskInfo, flowControlParam);
        }
        if (handler(taskInfo)) {
           // 记录

        }
        String batchNum=taskInfo.getBatchNum();
        Integer channel=taskInfo.getNotifyChannel();
        Long startTime=taskInfo.getStartTime();
        Long endTime=System.currentTimeMillis();
        log.info("------notify process batchNum:{}-channel:{}-time：{}ms",batchNum,channel,endTime-startTime);
    }


    /**
     * 统一处理的handler接口
     *
     * @param taskInfo
     * @return
     */
    public abstract boolean handler(TaskInfo taskInfo);


}
